package com.zlsoft.web;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;

import androidx.preference.PreferenceManager;


import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.UUID;


public class Common {
    private static final String TAG = "Common";
    private static SharedPreferences preferences;
    public static PackageInfo PackageInfo;

    public static void Init(Context context) {
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
        PackageInfo = GetPackageInfo(context);
        CheckDeviceID(context);
    }

    public static SharedPreferences getPreferences(Context context) {
        if (preferences == null)
            preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences;
    }

    public static void SetPreferenceValue(String strKey, String strValue) {
        SharedPreferences.Editor editor = Common.preferences.edit();
        editor.putString(strKey, strValue);
        editor.commit();
    }

    public static String GetServerAddress(Context context) {
        String strAddress = Common.preferences.getString("address", null);
        return strAddress;
    }

    public static PackageInfo GetPackageInfo(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info;
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e(TAG, "GetVersionName: ", ex);
            return null;
        }
    }

    public static void CheckDeviceID(Context context) {
        String strDeviceID = Common.preferences.getString("deviceid", "");
        if (strDeviceID.isEmpty()) {
            String strID = Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
            if (strID == null || strID.isEmpty())
                strID = UUID.randomUUID().toString();
            SetPreferenceValue("deviceid", strID);
        }
    }

    public static <T> byte[] Concat(byte[] first, byte[] second) {
        byte[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

    public static short HostToNetworkOrder(short host) {
        return (short) (((host & 0xFF) << 8) | ((host >> 8) & 0xFF));
    }

    public static byte[] UnsignedShortToByte2(int s) {
        byte[] targets = new byte[2];
        targets[0] = (byte) (s >> 8 & 0xFF);
        targets[1] = (byte) (s & 0xFF);
        return targets;
    }

    public static int Byte2ToUnsignedShort(byte[] bytes, int offset) {
        int high = bytes[offset];
        int low = bytes[offset + 1];
        return (high << 8 & 0xFF00) | (low & 0xFF);
    }

    public static Boolean HasPrefix(byte[] bytes, byte[] prefix) {
        if (bytes.length <= prefix.length) return false;
        byte[] bytesNew = Arrays.copyOf(bytes, prefix.length);
        if (Arrays.equals(bytesNew, prefix)) return true;
        return false;
    }

    public static byte[] EncodeNetWorkData(String strData) {
        byte[] data = strData.getBytes();
        byte[] dataLength = Common.UnsignedShortToByte2(data.length);
        data = Common.Concat(dataLength, data);
        return data;
    }

    public static String DecodeNetWorkData(byte[] bytes) {
        int intLength = Common.Byte2ToUnsignedShort(bytes, 0);
        String strData = new String(bytes, 2, intLength);
        return strData;
    }

    public static String getFileRealNameFromUrl(URLConnection urlConnection) throws UnsupportedEncodingException {
        String fileName = urlConnection.getHeaderField("Content-Disposition");
        if (fileName == null || fileName.length() < 1) {
            // 通过截取URL来获取文件名
            URL url2 = urlConnection.getURL();// 获得实际下载文件的URL
            String file1 = url2.getFile();
            fileName = file1.substring(file1.lastIndexOf("/") + 1);
            fileName = URLDecoder.decode(fileName, "UTF-8");
        } else {
            fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=") + 9), "UTF-8");
            // 有些文件名会被包含在""里面，所以要去掉，不然无法读取文件后缀
            fileName = fileName.replace("\"", "");
        }
        return fileName;
    }

    public static String getRealFilePath( final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
